<?php
Yii::app()->theme = Common::getTheme();
class SiteController extends Controller
{
	public $layout='column1';

	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
        
        public function actionIndex(){
            $this->pageTitle = "Game bài, Chơi bài online, Đánh bài miễn phí"; 
            Yii::app()->clientScript->registerMetaTag($this->pageTitle, 'title');            
            Yii::app()->clientScript->registerMetaTag("Hệ thống game bài phong phú: tiến lên, sâm lốc, tá lả, xì tố, mậu binh, liêng, chắn, bài cào...Đăng ký miễn phí, tặng 50.000 Xu hàng ngày.", 'description');
            Yii::app()->clientScript->registerMetaTag("game bai, choi bai, danh bai, game bai mien phi, game bai online, tien len, sam loc, ta la, xi to, mau binh, lieng, chan, bai cao", 'keywords');        
            
            $device = $this->getDevice();
            $banners = Banner::model()->findAll('status=1 AND type=1');
            if($device == "diff"){
                $pcode = Yii::app()->request->getParam('pcode');
                if(!isset($pcode)){ 
                    $pcode = 'window';
                }
                
                $criteria = new CDbCriteria();
                $criteria->select = 'game_platform.id, game_platform.game_id, game_platform.platform_id, game_platform.market_url, game_platform.bundle_id, game_platform.order';
                $criteria->alias = 'game_platform';
                $criteria->with = array('game'=>array('alias'  => 'game', 
                                                        'select'=>'name,status,image,slug,alt',
                                                        'joinType'=> 'INNER JOIN' 
                                                        ),
                                        'platform'=>array('alias'  => 'platform', 
                                                        'select'=>'name',
                                                        'joinType'=> 'INNER JOIN' 
                                                        )                    
                                        );                 
                //$criteria->join = "INNER JOIN game on game_platform.game_id = game.id";
                //$criteria->join .= " INNER JOIN platform on game_platform.platform_id = platform.id";
                $criteria->addCondition('game.status != 0');                
                if($pcode != 'window'){
                    $criteria->addCondition('platform.code_identifier ="'.$pcode.'"');
                    $criteria->order = 'game_platform.order ASC';                    
                }
                $criteria->group = 'game_platform.game_id';
                
                //$model = GamePlatform::model()->findAll($criteria); 
                $model = new CActiveDataProvider('GamePlatform', array(
                        'criteria' => $criteria,
                        'pagination' => array(
                            'pageSize' => 16,
                        ),                    
                    ));      
                
                $category2 = PostCategory::model()->find('code_identifier = "tin_tuc"');
                $dataPost2 = new CActiveDataProvider('Post', array(
                    'criteria' => array(
                        'order' => 'create_time DESC',
                        'condition' => 'status = 1 AND category_id = '.$category2->id,                        
                    ),
                    'pagination' => array(
                        'pageSize' => 10,
                    ),                    
                ));
                
                $category = PostCategory::model()->find('code_identifier = "huong_dan"');
                $dataPost = new CActiveDataProvider('Post', array(
                    'criteria' => array(
                        'order' => 'create_time DESC',
                        'condition' => 'status = 1 AND category_id = '.$category->id,                        
                    ),
                    'pagination' => array(
                        'pageSize' => 10,
                    ),                    
                ));
                                                
                $this->render('index', array('model'=>$model, 'device'=>$device, 'banners'=>$banners, 'dataPost'=>$dataPost, 'dataEvent'=>$dataPost2));
                exit();
            }elseif($device=="j2me"){
                $criteria = new CDbCriteria();
                $criteria->alias = 'game_platform';
                $criteria->join = "INNER JOIN game on game_platform.game_id = game.id";
                $criteria->join .= " INNER JOIN platform on game_platform.platform_id = platform.id";
                $criteria->addCondition('game.status != 0');
                $criteria->addCondition('platform.code_identifier ="'.$device.'"');
                $criteria->order = 'game_platform.order ASC';
                //$model = GamePlatform::model()->findAll($criteria); 
                $model = new CActiveDataProvider('GamePlatform', array(
                        'criteria' => $criteria,
                        'pagination' => array(
                            'pageSize' => 10,
                        ),                    
                    ));                
            }else{
                $criteria = new CDbCriteria();
                $criteria->alias = 'game_platform';
                $criteria->join = "INNER JOIN game on game_platform.game_id = game.id";
                $criteria->join .= " INNER JOIN platform on game_platform.platform_id = platform.id";
                $criteria->addCondition('game.status != 0');
                $criteria->addCondition('platform.code_identifier ="'.$device.'"');
                $criteria->order = 'game_platform.order ASC';
                $model = GamePlatform::model()->findAll($criteria);               
            }                                    
                                
            $this->render('index', array('model'=>$model, 'device'=>$device, 'banners'=>$banners));            
        }
        
        public function actionDetail(){                                
            $id = Yii::app()->request->getParam('id');            
            if(!isset($id))
                Common::alert('Đường dẫn không tồn tại', Yii::app()->homeUrl);
            //$model = Game::model()->findByPk($id);
            $model = Game::model()->find('slug=:slug', array(':slug'=>$id));
            if(!$model){
                $this->redirect(Yii::app()->homeUrl);
            }
            $this->pageTitle = strip_tags(trim(html_entity_decode($model->meta_title, ENT_QUOTES, 'UTF-8'), "\xc2\xa0"));
            Yii::app()->clientScript->registerMetaTag(strip_tags(trim(html_entity_decode($model->meta_title, ENT_QUOTES, 'UTF-8'), "\xc2\xa0")), 'title');            
            Yii::app()->clientScript->registerMetaTag(strip_tags(trim(html_entity_decode($model->meta_description, ENT_QUOTES, 'UTF-8'), "\xc2\xa0")), 'description');
            Yii::app()->clientScript->registerMetaTag(strip_tags(trim(html_entity_decode($model->meta_keyword, ENT_QUOTES, 'UTF-8'), "\xc2\xa0")), 'keywords');
            
            $device = $this->getDevice();
            if($device == "diff"){                
                $this->render('detail', array('model'=>$model)); 
            }else{
                $criteria = new CDbCriteria();
                $criteria->alias = 'game_platform';
                $criteria->join = "INNER JOIN game on game_platform.game_id = game.id";
                $criteria->join .= " INNER JOIN platform on game_platform.platform_id = platform.id";
                $criteria->addCondition('game.status != 0');
                $criteria->addCondition('platform.code_identifier ="'.$device.'"');
                $criteria->addCondition('game.slug != "'.$id.'"');
                $criteria->limit = 10;
                $criteria->order = 'game_platform.order ASC';
                $modelGameDiff = GamePlatform::model()->findAll($criteria);               

                $this->render('detail', array('model'=>$model,'device'=>$device, 'modelGameDiff'=>$modelGameDiff));
            }
        }      
        
        function getDevice(){
            if(Common::isRunningiOS()){
                $device = "ios";                      
            }
            elseif(Common::isRunningAndroidOS()){                
                $device = "android";                                
            }elseif(Common::isSymbian()){
                $device = "j2me";
            }else{                
                $device = "diff";
            }  
            return $device;
        }

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
                    $this->render('error', $error);
                    //$this->redirect('route', true, 301);
	    }
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
            $model=new ContactForm;
            if(isset($_POST['ContactForm']))
            {
                $model->attributes=$_POST['ContactForm'];
                if($model->validate())
                {
                    $headers="From: {$model->email}\r\nReply-To: {$model->email}";
                    mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
                    Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
                    $this->refresh();
                }
            }
            $this->render('contact',array('model'=>$model));
	}
        
        public function actionDownload(){             
            $game =  Yii::app()->request->getParam('game'); 
            $option = Yii::app()->request->getParam('option');
            if(isset($game)){
                $gameModel = Game::model()->find('code_identifier=:code_identifier',array(':code_identifier'=>$game));
                if(!isset($gameModel)){
                    Common::alert('Không tồn tại game!', Yii::app()->homeUrl);
                }
                $platform = $this->getDevice();                
                if($platform == 'diff')
                    $platform = Yii::app()->request->getParam('pcode');
                $gameVersion = $gameModel->getCurrentVersion($platform);
                if(!$gameVersion){
                    Common::alert('Không tồn tại version hiện tại', Yii::app()->homeUrl);
                }else{       
                    $gameVersion->download_times += 1;
                    $gameVersion->save();
                    if($platform != 'j2me'){
                        if(!isset($option))
                            $ext = pathinfo($gameVersion->file_path, PATHINFO_EXTENSION);    
                        else
                            $ext = pathinfo($gameVersion->file_path2, PATHINFO_EXTENSION);                        
                         header('Content-Description: File Transfer');
                         header('Content-Type: application/octet-stream');
                         header('Content-Disposition: attachment; filename=' . ($gameModel->code_identifier.'-'.$gameVersion->getCurrentVersion().'.'.$ext));
                         header('Content-Transfer-Encoding: binary');
                         header('Expires: 0');
                         header('Cache-Control: must-revalidate');
                         header('Pragma: public');
                         if(!isset($option))
                            header('Content-Length: ' . filesize($gameVersion->file_path));
                         else
                            header('Content-Length: ' . filesize($gameVersion->file_path2));
                         ob_clean();
                         flush();
                         if(!isset($option))
                            readfile($gameVersion->file_path);               
                         else
                            readfile($gameVersion->file_path2);               
                    }else{                     
                        if(!isset($option))
                            $this->redirect(Yii::app()->createUrl($gameVersion->file_path));
                        else
                            $this->redirect(Yii::app()->createUrl($gameVersion->file_path2));
                    }
                }
            }          
        }
        
        public function actionSearch(){
            $keyword = Yii::app()->request->getParam('keyword');
            $criteria = new CDbCriteria();            
            $criteria->alias = 'game_platform';
            $criteria->join = "INNER JOIN game on game_platform.game_id = game.id";
            $criteria->join .= " INNER JOIN platform on game_platform.platform_id = platform.id";
            $criteria->addCondition('game.status != 0');
            $criteria->addCondition('game.name like :keyword');
            $criteria->params = array(':keyword'=>'%'.$keyword.'%'); 
            //$criteria->group = 'game.id';
            
            $criteria->order = 'game_platform.order ASC';            
            $model = new CActiveDataProvider('GamePlatform', array(
                    'criteria' => $criteria,
                    'pagination' => array(
                        'pageSize' => 16,
                    ),                    
                ));            
            $category = PostCategory::model()->find('code_identifier = "huong_dan"');
            $dataPost = new CActiveDataProvider('Post', array(
                'criteria' => array(
                    'order' => 'create_time DESC',
                    'condition' => 'status = 1 AND category_id = '.$category->id,                        
                ),
                'pagination' => array(
                    'pageSize' => 10,
                ),                    
            ));
            $banners = Banner::model()->findAll('status=1 AND type=1');
            $this->render('index', array('model'=>$model, 'banners'=>$banners, 'dataPost'=>$dataPost));            
                
        }                
        
        public function actionFeedback(){
            $return = array();
            $name = Yii::app()->request->getParam('name');
            $email = Yii::app()->request->getParam('email');
            $content = Yii::app()->request->getParam('content');
            if(!isset($name) || !isset($email) || !isset($content)){
                $return['code'] = -1;
                $return['message'] = 'Mời bạn nhập đầy đủ thông tin';                
            }else{
                if(filter_var($email, FILTER_VALIDATE_EMAIL)){
                    $feedback = new Feedback();
                    $feedback->name = $name;
                    $feedback->email = $email;
                    $feedback->content = $content;
                    if($feedback->save()){
                        $return['code'] = 0;
                        $return['message'] = 'Cảm ơn bạn đã gửi feedback tới casino888.vn';
                    }else{
                        $return['code'] = -1;
                        $return['message'] = 'Gửi feedback thất bại';
                    }
                }else{
                     $return['code'] = -1;
                     $return['message'] = 'Email của bạn sai định dạng!';
                }
            }
            echo json_encode($return);
        }
        
        public function actionLogout(){
            Yii::app()->user->logout();
            $this->redirect(Yii::app()->homeUrl);
        }                
	
}
